package com.fc.redis.service;

import com.alibaba.fastjson.JSONObject;
import com.fc.redis.entity.TbUser;
import com.fc.redis.mapper.TbUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.Map;

/**
 * @program: fc-redis->ConcurrentCacheTestService
 * @description: 测试默认缓存manager——concurrentCache
 * @author: G_Y
 * @create: 2019-09-10 14:25
 **/
@Service
@CacheConfig(cacheManager = "concurrentMapCacheManager", cacheNames = {"localDefaultCache"})
@Slf4j
public class ConcurrentCacheTestService {

    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private ConcurrentMapCacheManager concurrentMapCacheManager;

    @PostConstruct
    public void init() {
        Cache localDefaultCache = concurrentMapCacheManager.getCache("localDefaultCache");
        log.info(localDefaultCache.getClass().getName());
    }

    @Cacheable(key = "#id")
    public TbUser getUser(Integer id) {
        log.info("This is use ConcurrentCache cache user");
        TbUser tbUser = userMapper.selectByPrimaryKey(id);
        return tbUser;
//        return this.getUserPrivate(id);
    }

//    @Cacheable(key = "#id")
//    public TbUser getUserPrivate(Integer id){
//        log.info("This is use ConcurrentCache cache user");
//        TbUser tbUser = userMapper.selectByPrimaryKey(id);
//        return tbUser;
//    }

    @CachePut(key = "#user.id")
    public TbUser addOrUpdateUserById(TbUser user) {
        Map<String, Object> map = (Map<String, Object>) JSONObject.toJSON(user);
        log.info("map = {}", map);
        user.setUpdateTime(new Date());
        if (user.getId() == null || user.getId() == 0) {
            userMapper.insertSelective(user);
            return user;
        }
        userMapper.updateByPrimaryKeySelective(user);
        return user;
    }

    // allEntries：
    //是否清空所有缓存内容，缺省为 false，如果指定为 true，则方法调用后将立即清空所有缓存
    //beforeInvocation：
    //是否在方法执行前就清空，缺省为 false，如果指定为 true，则在方法还没有执行的时候就清空缓存，缺省情况下，如果方法执行抛出异常，则不会清空缓存
    @CacheEvict(key = "#id")
    public boolean deleteUserById(Integer id) {
        int i = userMapper.deleteByPrimaryKey(id);
        if (i > 0)
            return true;
        return false;
    }

}
